#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace log_ns;
const static u_int16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

class UdpSever : public nocopy
{
public:
    UdpSever(uint16_t port = defaultport) : _port(port), _sockfd(defaultfd),_isrunning(false)
    {
    }
    
    void InitServer()
    {
        // 1.创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
           LOG(FATAL,"socket error\n");
           exit(SOCKET_ERROR);
        }
        LOG(DEBUG,"socket create success,_sockfd:%d\n",_sockfd);
    
        //2.bind
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=INADDR_ANY; //服务器端，进行任意IP地址绑定

        int n=::bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG,"socket bind success\n");
    }
    void Start()
    {
        _isrunning=true;
        char inbuff[1024];
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            ssize_t n=recvfrom(_sockfd,inbuff,sizeof(inbuff)-1,0,(struct sockaddr*)&peer,&len);
            if(n>0)
            {
                InetAddr addr(peer);
                inbuff[n]=0;
                std::cout<< "[" << addr.Ip() << "]#" << inbuff << std::endl;
                std::string echo_string="[udp_server echo]";
                echo_string+=inbuff;
                sendto(_sockfd,echo_string.c_str(),echo_string.size(),0,(struct sockaddr*)&peer,len);

            }
            else{
                std::cout << "recvform , error" << std::endl;
            }
        }
    }
    ~UdpSever()
    {
        if(_sockfd>defaultfd)
        ::close(_sockfd);
    }

private:
    uint16_t _port;
    int _sockfd;
    bool _isrunning;
};